package io.gitee.itxinmeng.encrypt.spring.boot.common;

import cn.hutool.json.JSONUtil;
import io.gitee.itxinmeng.encrypt.spring.boot.autoconfigure.properties.EncryptProperties;
import io.gitee.itxinmeng.encrypt.spring.boot.common.encrypt.EncryptMethodFactory;
import io.gitee.itxinmeng.encrypt.spring.boot.common.encrypt.strategy.IEncryptStrategy;
import io.gitee.itxinmeng.encrypt.spring.boot.util.ServletUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * Rewrite body Object to decrypt body content
 * @author mx
 */
public class BodyHttpInputMessage implements HttpInputMessage{
    private static final Logger LOGGER = LoggerFactory.getLogger(BodyHttpInputMessage.class);

    private HttpHeaders headers;
    private InputStream body;

    @Override
    public InputStream getBody() {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }

    public BodyHttpInputMessage(HttpInputMessage inputMessage, EncryptProperties config) {
        this.headers = inputMessage.getHeaders();
        String content = ServletUtil.getBodyString(inputMessage);
        if (JSONUtil.isTypeJSON(content)) {
            LOGGER.info("Dectypt Fail,Body is not encrypt,body:({})", content);
            body = new ByteArrayInputStream(content.getBytes());
            return;
        }
        IEncryptStrategy encryptStrategy = EncryptMethodFactory.INSTANCE.getEncryptStrategy(config.getMethod());
        String decryptContent = encryptStrategy.decryptBody(headers, content);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.info("Before decrypt：({})，After decrypt：({})", content, decryptContent);
        }
        this.body = new ByteArrayInputStream(decryptContent.getBytes());
    }
}
